import React, { Component } from 'react'
import { FormInstance, message, Spin } from 'antd';
import { Form, Input, Button, Select } from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import { queryCategories } from '../../../../../api/home';
import ArticleCate from '../../../../../types/ArticleCate';
import { editArticle, queryArticlesOnID } from '../../../../../api/blog';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import Article from '../../../../../types/Article';
import ArticleDisplay from '../../../../../Components/ArticleDisplay';

const { Option } = Select;


interface IProps extends RouteComponentProps<{ articleID: string }> { }
interface IState {
    isLoading: boolean
    cates: ArticleCate[]
    article: Article
}
class EditArticle extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            isLoading: true,
            cates: [],
            article: {
                articleID: -1,
                cate: {
                    cateID: -1,
                    cateName: ''
                },
                views: 0,
                omit: false,
                title: '',
                time: '',
                content: ''
            }
        }
    }

    async componentDidMount() {
        const cates = await queryCategories();  //请求所有种类
        this.setState({
            cates,
        })
        //请求现有文章
        const originArticle = await queryArticlesOnID(parseInt(this.props.match.params.articleID));
        if (!!originArticle) {
            this.setState({
                article: originArticle,
                isLoading: false
            }, () => {
                this.formRef.current?.setFieldsValue({
                    title: this.state.article.title,
                    markdown: this.state.article.content,
                    cateID: this.state.article.cate.cateID
                })
            })
        }

    }
    formRef = React.createRef<FormInstance>();  //表单引用

    onFinish = async (values: any) => {
        this.setState({ isLoading: true });
        const res = await editArticle(values.title, values.markdown, values.cateID, parseInt(this.props.match.params.articleID))
        this.setState({ isLoading: false });
        if (!!res) {  //编辑成功
            message.success('编辑成功');
        } else {
            //编辑失败
            message.error('编辑失败！')
        }
    }
    onContentChange: React.ChangeEventHandler<HTMLTextAreaElement> = (e) => {
        this.setState((state, props) => ({
            ...state,
            article: {
                ...state.article,
                content: e.target.value
            }
        }))
    }
    render() {
        const { isLoading } = this.state;
        const { content } = this.state.article;
        return (
            <div className="maniFormBox">
                <Spin spinning={isLoading} >
                    <Form
                        ref={this.formRef}
                        layout="vertical"
                        name="editArticle"
                        onFinish={this.onFinish}
                    >
                        <Form.Item
                            label="文章标题"
                            name="title"
                            rules={[{ required: true, message: '标题必填' }]}
                        >
                            <Input />
                        </Form.Item>

                        <div className="editArticleRow" style={{ display: 'flex' }}>
                            <Form.Item
                                label="markdown"
                                name="markdown"
                                rules={[{ required: true, message: '请输入内容' }]}
                                style={{ width: '48%' }}
                            >
                                <TextArea rows={25} onChange={this.onContentChange} />
                            </Form.Item>
                            <div className="EditArticlePreview" style={{ width: '50%', paddingLeft: '2%' }}>
                                <h4>文章预览</h4>
                                <div style={{ maxHeight: '560px', overflow: 'auto' }} >
                                    <ArticleDisplay content={content} loading={false} />
                                </div>
                            </div>
                        </div>

                        <Form.Item name="cateID" label="类别标签" rules={[{ required: true, message: "请选择标签" }]}>
                            <Select
                                placeholder="请选择标签"
                            >
                                {this.state.cates.map(cate => (
                                    <Option key={cate.cateID} value={cate.cateID}>{cate.cateName}</Option>
                                ))}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                提交
                        </Button>
                        </Form.Item>
                    </Form>
                </Spin>
            </div>
        )
    }
}
export default withRouter(EditArticle);